package com.party.web.web.controller.crowdfund;


import com.alibaba.fastjson.JSON;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.crowdfund.*;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.ICrowfundFollowUpService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.order.IOrderFormService;
import com.party.web.biz.crowdfund.ProjectBizService;
import com.party.web.biz.file.ExcelExportService;
import com.party.web.biz.order.OrderBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.crowdfund.ProjectForActivityOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/***
 * 众筹截止跟进
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "crowdfund/followUp")
public class CrowfundFollowUpController {

    @Autowired
    private ICrowfundFollowUpService crowfundFollowUpService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private ExcelExportService excelExportService;
    @Autowired
    private IMemberGroupService memberGroupService;

    protected static Logger logger = LoggerFactory.getLogger(CrowfundFollowUpController.class);


    /**
     * 众筹结束跟进列表
     *
     * @param crowdfundEvent 众筹事件
     * @param page           分页参数
     * @return 事件列表
     */
    @RequestMapping(value = "list")
    public ModelAndView endList(CrowdfundEventWithMemberPartner crowdfundEvent, Page page, CommonInput input) {

        try {
            page.setLimit(20);
            ModelAndView modelAndView = new ModelAndView("crowdfund/eventEndList");
            //当前登录用户
            String memberId = RealmUtils.getCurrentUser().getId();
            if (StringUtils.isEmpty(memberId)) {
                return null;
            }
            Map<String, Object> params = CommonInput.appendParams(input);
            List<String> orgIds = memberGroupService.getChildWithMy(memberId);
            params.put("orgIds", orgIds);

            crowdfundEvent.setIsMultiple(YesNoStatus.NO.getCode());
            List<Map<String, Object>> crowdfundEventList = crowfundFollowUpService.endList(crowdfundEvent, params, page);
            for (Map<String, Object> stringObjectMap : crowdfundEventList) {
/*                String endDate = null;
                if (stringObjectMap.get("endTime") != null) {
                    endDate = stringObjectMap.get("endTime").toString();
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse = sdf.parse(endDate);
                long endTime = parse.getTime();
                long startTimeMillis = System.currentTimeMillis();
                long time = startTimeMillis - endTime;
                long days = time / (1000 * 60 * 60 * 24);
                stringObjectMap.put("format", days);*/

                String eventId = stringObjectMap.get("eventId").toString();
/*                //众筹成功人数
                Integer zcCount = projectService.countForEvent(eventId.toString(), Constant.IS_CROWFUND_SUCCESS);
                //直接付款人数
                Integer zjCount = projectService.dpCountForEvent(eventId.toString(), Constant.IS_CROWFUND_SUCCESS);
                //成功人数
                stringObjectMap.put("successNum", zcCount + zjCount);
                //成功金额
                ProjectAnalyze projectAnalyze = new ProjectAnalyze();
                projectAnalyze.setEventId(eventId);
                projectAnalyze.setIsSuccess(Constant.IS_CROWFUND_SUCCESS);
                stringObjectMap.put("successMoney", projectService.sumProjectOREventAmount(projectAnalyze, 1));*/
                //剩余金额
                Double payMoney = orderFormService.findPaymentByEventId(eventId);
                stringObjectMap.put("remainMoney", BigDecimalUtils.round(payMoney, 2));

            }
            modelAndView.addObject("event", crowdfundEvent);
            modelAndView.addObject("list", crowdfundEventList);
            modelAndView.addObject("page", page);
            modelAndView.addObject("input", input);
            return modelAndView;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @ResponseBody
    @RequestMapping(value = "endListExport")
    public AjaxResult endListExport(CrowdfundEventWithMemberPartner crowdfundEvent, CommonInput input) {

        //当前登录用户
        String memberId = RealmUtils.getCurrentUser().getId();
        if (StringUtils.isEmpty(memberId)) {
            return null;
        }
        Map<String, Object> params = CommonInput.appendParams(input);
        List<String> orgIds = memberGroupService.getChildWithMy(memberId);
        params.put("orgIds", orgIds);

        crowdfundEvent.setIsMultiple(YesNoStatus.NO.getCode());
        List<Map<String, Object>> crowdfundEventList = crowfundFollowUpService.endList(crowdfundEvent, params, null);

        List<CrowdfundEndFollowOutput> cefoList = new ArrayList<>();
        try {
            for (Map<String, Object> stringObjectMap : crowdfundEventList) {
/*                String endDate = null;
                if (stringObjectMap.get("endTime") != null) {
                    endDate = stringObjectMap.get("endTime").toString();
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse = sdf.parse(endDate);

                long endTime = parse.getTime();
                long startTimeMillis = System.currentTimeMillis();
                long time = startTimeMillis - endTime;
                long days = time / (1000 * 60 * 60 * 24);
                stringObjectMap.put("format", days);*/

                String eventId = stringObjectMap.get("eventId").toString();
/*                //众筹成功人数
                Integer zcCount = projectService.countForEvent(eventId.toString(), Constant.IS_CROWFUND_SUCCESS);
                //直接付款人数
                Integer zjCount = projectService.dpCountForEvent(eventId.toString(), Constant.IS_CROWFUND_SUCCESS);
                //成功人数
                stringObjectMap.put("successNum", zcCount + zjCount);
                //成功金额
                ProjectAnalyze projectAnalyze = new ProjectAnalyze();
                projectAnalyze.setEventId(eventId);
                projectAnalyze.setIsSuccess(Constant.IS_CROWFUND_SUCCESS);
                stringObjectMap.put("successMoney", projectService.sumProjectOREventAmount(projectAnalyze, 1));
                //剩余金额*/
                Double payMoney = orderFormService.findPaymentByEventId(eventId);
                stringObjectMap.put("remainMoney", BigDecimalUtils.round(payMoney, 2));

                CrowdfundEndFollowOutput crowdfundEndFollowOutput = JSON.parseObject(JSON.toJSONString(stringObjectMap), CrowdfundEndFollowOutput.class);

                cefoList.add(crowdfundEndFollowOutput);
            }

            String fileName = "众筹结束跟进记录.xlsx";

            ExportExcel exportExcel = new ExportExcel(fileName, CrowdfundEndFollowOutput.class).setDataList(cefoList);
            String allPath = excelExportService.getExcelPath(fileName, "project", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (Exception e) {
            logger.error("导出众筹异常", e);
        }

        return AjaxResult.error("导出异常");
    }

    /**
     * 众筹结束跟状态改变
     */
    @ResponseBody
    @RequestMapping(value = "update")
    public AjaxResult update(String id, int followState) {
        int i = crowfundFollowUpService.update(id, followState);
        if (i == 1) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("更新异常");
        }
    }


    /**
     * 根据事件查询众筹列表
     *
     * @param projectWithAuthor 查询数据
     * @param page              分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "listForEvent")
    public ModelAndView listForEvent(ProjectWithAuthor projectWithAuthor, Page page) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/zcCrowdfundFollowUp");
        page.setLimit(20);
        projectWithAuthor.setDistribution(true);
        if(StringUtils.isEmpty(projectWithAuthor.getEventId())){
            return null;
        }
        ProjectWithAuthor author = new ProjectWithAuthor();
        author.setEventId(projectWithAuthor.getEventId());
        author.setPayType(1);
        List<ProjectForActivityOutput> dpList = projectBizService.projectForActivityList(author, null);

        Integer isSuccess = projectWithAuthor.getIsSuccess();

        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }
        projectWithAuthor.setPayType(0);//查询普通众筹

        //众筹成功
        if (null != projectWithAuthor.getPayStatus() && "1".equals(projectWithAuthor.getPayStatus())) {
            projectWithAuthor.setIsSuccess(1);
        }
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, page);

        Integer representNum = distributorRelationService.countForEvent(projectWithAuthor.getEventId());
        projectWithAuthor.setIsSuccess(isSuccess);


        //成功金额
        ProjectAnalyze projectAnalyze = new ProjectAnalyze();
        projectAnalyze.setEventId(projectWithAuthor.getEventId());
        projectAnalyze.setIsSuccess(Constant.IS_CROWFUND_SUCCESS);
        projectAnalyze.setPayType(0);
        Double successfulAmount = projectService.sumProjectOREventAmount(projectAnalyze, 1);
        //众筹金额
        modelAndView.addObject("representNum", representNum);
        modelAndView.addObject("projectNum", page.getTotalCount());
        modelAndView.addObject("directNum", dpList.size());
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);//回传查询参数
        modelAndView.addObject("list", projectForActivityOutputList);
        modelAndView.addObject("page", page);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectWithAuthor.getEventId());
        modelAndView.addObject("crowdfundEvent", crowdfundEvent);
        modelAndView.addAllObjects(orderBizService.getOrderData(projectWithAuthor.getEventId(), 0));

        modelAndView.addObject("successfulAmount", successfulAmount);
        return modelAndView;
    }
}
